<template>
  <el-dialog
    v-model="dialogVisible"
    :title="mode === 'create' ? '添加配置' : '编辑配置'"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      label-position="right"
    >
      <el-form-item label="Key" prop="key">
        <el-input
          v-model="formData.key"
          placeholder="请输入配置Key（必填）"
          :disabled="mode === 'edit'"
        />
        <div class="form-tip">Key用于唯一标识配置项，创建后不可修改</div>
      </el-form-item>

      <el-form-item label="类型" prop="type">
        <el-input
          v-model="formData.type"
          placeholder="请输入配置类型（可选）"
        />
        <div class="form-tip">用于对配置进行分类，如：system、app、user等</div>
      </el-form-item>

      <el-form-item label="值" prop="value">
        <el-input
          v-model="valueString"
          type="textarea"
          :rows="8"
          placeholder="请输入配置值（支持JSON格式）"
          @blur="handleValueBlur"
        />
        <div class="form-tip">
          支持字符串、数字、布尔值或JSON对象。输入JSON时请确保格式正确。
        </div>
        <div v-if="valueError" class="form-error">{{ valueError }}</div>
      </el-form-item>

      <el-form-item label="描述" prop="desc">
        <el-input
          v-model="formData.desc"
          type="textarea"
          :rows="3"
          placeholder="请输入配置描述（可选）"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from 'vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { keyValueApi, type KeyValue, type CreateKeyValueData, type UpdateKeyValueData } from '../../api/keyValue';

// Props
interface Props {
  modelValue: boolean;
  data?: KeyValue | null;
  mode?: 'create' | 'edit';
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  data: null,
  mode: 'create',
});

// Emits
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void;
  (e: 'success'): void;
}>();

// 表单引用
const formRef = ref<FormInstance>();

// 状态
const submitting = ref(false);
const valueError = ref('');

// 表单数据
const formData = reactive<{
  key: string;
  type: string;
  value: any;
  desc: string;
}>({
  key: '',
  type: '',
  value: null,
  desc: '',
});

// 值的字符串表示（用于textarea显示）
const valueString = ref('');

// 表单验证规则
const formRules: FormRules = {
  key: [
    { required: true, message: '请输入Key', trigger: 'blur' },
    { min: 1, max: 255, message: 'Key长度应在1-255个字符之间', trigger: 'blur' },
  ],
};

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val),
});

// 解析值字符串
const parseValue = (str: string): { value: any; error: string } => {
  if (!str || str.trim() === '') {
    return { value: null, error: '' };
  }

  const trimmed = str.trim();

  // 尝试解析为JSON
  try {
    const parsed = JSON.parse(trimmed);
    return { value: parsed, error: '' };
  } catch {
    // 如果不是JSON，尝试解析为其他类型
    // 数字
    if (/^-?\d+\.?\d*$/.test(trimmed)) {
      const num = Number(trimmed);
      if (!isNaN(num)) {
        return { value: num, error: '' };
      }
    }

    // 布尔值
    if (trimmed.toLowerCase() === 'true') {
      return { value: true, error: '' };
    }
    if (trimmed.toLowerCase() === 'false') {
      return { value: false, error: '' };
    }

    // null
    if (trimmed.toLowerCase() === 'null') {
      return { value: null, error: '' };
    }

    // 作为字符串处理
    return { value: trimmed, error: '' };
  }
};

// 值字符串变化处理
const handleValueBlur = () => {
  const { value, error } = parseValue(valueString.value);
  if (error) {
    valueError.value = error;
  } else {
    valueError.value = '';
    formData.value = value;
  }
};

// 初始化表单数据
const initFormData = () => {
  if (props.data && props.mode === 'edit') {
    formData.key = props.data.key || '';
    formData.type = props.data.type || '';
    formData.desc = props.data.desc || '';
    formData.value = props.data.value;

    // 将值转换为字符串显示
    if (formData.value === null || formData.value === undefined) {
      valueString.value = '';
    } else if (typeof formData.value === 'string') {
      valueString.value = formData.value;
    } else {
      try {
        valueString.value = JSON.stringify(formData.value, null, 2);
      } catch {
        valueString.value = String(formData.value);
      }
    }
  } else {
    formData.key = '';
    formData.type = '';
    formData.value = null;
    formData.desc = '';
    valueString.value = '';
  }
  valueError.value = '';
};

// 监听对话框打开
watch(() => props.modelValue, (val) => {
  if (val) {
    initFormData();
    // 重置表单验证状态
    nextTick(() => {
      formRef.value?.clearValidate();
    });
  }
});

// 监听数据变化
watch(() => props.data, () => {
  if (props.modelValue) {
    initFormData();
  }
}, { deep: true });

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  // 验证表单
  try {
    await formRef.value.validate();
  } catch {
    return;
  }

  // 解析值
  const { value, error } = parseValue(valueString.value);
  if (error) {
    valueError.value = error;
    ElMessage.error('配置值格式错误，请检查');
    return;
  }

  formData.value = value;

  submitting.value = true;
  try {
    if (props.mode === 'create') {
      const createData: CreateKeyValueData = {
        key: formData.key,
        value: formData.value,
        type: formData.type || undefined,
        desc: formData.desc || undefined,
      };
      await keyValueApi.createOrUpdate(createData);
      ElMessage.success('创建成功');
    } else {
      if (!props.data?.id) {
        ElMessage.error('无效的配置项ID');
        return;
      }
      const updateData: UpdateKeyValueData = {
        id: props.data.id,
        key: formData.key,
        value: formData.value,
        type: formData.type || undefined,
        desc: formData.desc || undefined,
      };
      await keyValueApi.update(props.data.id, updateData);
      ElMessage.success('更新成功');
    }

    emit('success');
    handleClose();
  } catch (error: any) {
    console.error('提交失败:', error);
    ElMessage.error(error.message || '操作失败');
  } finally {
    submitting.value = false;
  }
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  if (formRef.value) {
    formRef.value.resetFields();
    formRef.value.clearValidate();
  }
  valueError.value = '';
};
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
  line-height: 1.4;
}

.form-error {
  font-size: 12px;
  color: var(--el-color-danger);
  margin-top: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>

